<template>
  <customizeDialog
    :visible="dialogMapVisible"
    @update:visible="dialogMapVisible = $event"
    ref="dialog"
    :title="`${headerTitle}`"
    :width="'1200px'"
    top="100px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :has-footer="false"
    customPadding="0px"
  >
    <div
      v-loading="loading"
      element-loading-text="文件正在解析中，请稍后..."
    >
      <MapView
        :viewer-id="viewerId"
        :key="countMapLoad"
        @onload="onMapLoad"
      />
      <Utool
        :viewerId="viewerId"
        :position="{ top: '60px', right: '20px' }"
        :t="[]"
        :b="[
          {
            title: '初始位置',
            icon: 'dingwei'
          }
        ]"
        :showMore="false"
      ></Utool>
    </div>
    <div class="operate" v-if="!diasbled">
      <el-button
        @click="handleSureCoordinate"
        class="save-btn"
        >确定</el-button
      >
      <el-button
        @click="handleCancleCoordinate"
        class="cancle-btn"
        >取消</el-button
      >
    </div>
  </customizeDialog>
</template>
<script>
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import cacheUtil from '@/utils/cache'
import { homePosition } from '@/utils/constant'

let _layerManager, _viewer
const mapViewer = {}

export default {
  components: {
    MapView,
    Utool,
    customizeDialog
  },
  props: {
    address: {
      type: String
    },
    diasbled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      newLocation: '',
      dialogMapVisible: false,
      viewerId: 'locationMap',
      countMapLoad: 0,
      headerTitle: '项目位置',
      loading: false,
      cameraConfig: null,
      billboards: []
    }
  },
  methods: {
    onMapLoad({ id, viewer }) {
      _viewer = viewer
      mapViewer[this.viewerId] = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )

      this.billboards = mapViewer[
        this.viewerId
      ].scene.primitives.add(
        new Cesium.BillboardCollection()
      )
      mapViewer[
        this.viewerId
      ].screenSpaceEventHandler.setInputAction(
        this.leftClick,
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      )
      // this.setViewer(viewer)
      if (this.address) {
        this.billboards.add({
          id: 'location-point',
          width: 18,
          height: 18,
          position: Cesium.Cartesian3.fromDegrees(
            Number(this.address.split(',')[0]),
            Number(this.address.split(',')[1]),
            0
          ),
          image: require('@/assets/img/location.png'),
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM
        })
      }
      this.setViewer(viewer)
    },
    leftClick(movement) {
      if (this.diasbled) {
        return
      }
      const cartesian = mapViewer[
        this.viewerId
      ].camera.pickEllipsoid(movement.position)
      const cartographic =
        Cesium.Cartographic.fromCartesian(cartesian)
      const lng = Cesium.Math.toDegrees(
        cartographic.longitude
      ) // 经度
      const lat = Cesium.Math.toDegrees(
        cartographic.latitude
      ) // 纬度

      this.billboards && this.billboards.removeAll()
      this.billboards.add({
        id: 'location-point',
        width: 18,
        height: 18,
        position: Cesium.Cartesian3.fromDegrees(
          lng,
          lat,
          0
        ),
        image: require('@/assets/img/location.png'),
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM
      })
      this.newLocation = `${lng},${lat}`
    },
    // 打开弹窗
    handleShowMap() {
      this.dialogMapVisible = true
    },
    // 取消定位
    handleCancleCoordinate() {
      this.billboards && this.billboards.removeAll()
      this.dialogMapVisible = false
    },
    // 确定定位
    handleSureCoordinate() {
      this.dialogMapVisible = false
      this.$emit('sure', this.newLocation)
    },
    // 设置视角
    setViewer(viewer) {
      const cacheItem = cacheUtil.getItem('camera')
      if (cacheItem) {
        try {
          const config = JSON.parse(cacheItem)
          if (config.cameraHeight && config.centerPoint) {
            this.cameraConfig = config
          } else {
            this.cameraConfig = null
          }
        } catch (e) {
          console.error(e)
          this.cameraConfig = null
        }
      } else {
        this.cameraConfig = null
      }
      if (this.address) {
        // viewer.flyTo(this.billboards)
        viewer.camera.flyTo({
          destination: this.cameraConfig
            ? Cesium.Cartesian3.fromDegrees(
                Number(this.address.split(',')[0]),
                Number(this.address.split(',')[1]),
                Number(this.cameraConfig.cameraHeight)
              )
            : homePosition.destination,
          orientation: homePosition.orientation
        })
      } else {
        viewer.camera.flyTo({
          destination: this.cameraConfig
            ? Cesium.Cartesian3.fromDegrees(
                Number(
                  this.cameraConfig.centerPoint.split(
                    ','
                  )[0]
                ),
                Number(
                  this.cameraConfig.centerPoint.split(
                    ','
                  )[1]
                ),
                Number(this.cameraConfig.cameraHeight)
              )
            : homePosition.destination,
          orientation: homePosition.orientation
        })
      }
      viewer.scene.screenSpaceCameraController.enableCollisionDetection = true
      viewer.scene.globe.globeAlpha = 1
    }
  }
}
</script>
<style lang="scss" scoped>
.operate {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  ::v-deep {
    .save-btn {
      background: #497fa3;
      border: 1px solid #497fa3;
      color: white;
      font-size: 14px;
      width: 80px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 0px;
    }
    .cancle-btn {
      font-size: 14px;
      width: 80px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 1px solid #497fa3;
      color: #497fa3;
    }
  }
}
</style>
